const { sequelize } = require("@/db");
const { formatResponse } = require("@/utils/responseFormatter.js");

// 获取商品列表的路由
exports.getMall = async (ctx, next) => {
  const sql = `select * from mall order by id desc`;
  try {
    const results = await sequelize.query(sql, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (results === undefined) {
      formatResponse(ctx, 400, "获取商品失败,未找到商品");
    } else {
      formatResponse(ctx, 200, "获取商品成功", 20000, results);
    }
  } catch (error) {
    console.error("获取商品失败: ", error);
    formatResponse(ctx, 500, "数据库操作失败");
  }
};

// 新增商品的路由
exports.addMall = async (ctx, next) => {
  const sql =
    "insert into mall (name, price, pic, count, `desc`) VALUES (?, ?, ?, ?, ?)";
  const { name, price, pic, count, desc } = ctx.request.body;
  try {
    const result = await sequelize.query(sql, {
      replacements: [name, +price, pic, +count, desc],
      type: sequelize.QueryTypes.INSERT,
    });

    if (result && result[1] === 1) {
      formatResponse(ctx, 200, "商品新增成功", 20000);
    } else {
      formatResponse(ctx, 500, "商品新增失败");
    }
  } catch (error) {
    console.error(error);
    formatResponse(ctx, 500, "数据库操作失败");
  }
};
